package com.yan.deezer.network;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpResponse {


	private DefaultHttpClient client;
	private int code;
	private InputStream streamContent;
	private byte[] byteContent;
	private int contentLength;
	private String contentType;
	private Header[] headers;
	
	public HttpResponse (int code, Header[] headers, HttpEntity httpEntity, DefaultHttpClient client) throws IllegalStateException, IOException {
		this.client = client;
		this.code = code;
		this.contentLength = (int)httpEntity.getContentLength();
		this.streamContent = httpEntity.getContent();
        this.contentType = httpEntity.getContentType().getValue();
        this.headers = headers;
    }
	
	public void close(){
		if(client != null){
			client.getConnectionManager().shutdown();
		}
	}
	
	public void readBody() throws IOException{
		 byte[] buffer = new byte[8192];
         int count = 0;
         ByteArrayOutputStream content = new ByteArrayOutputStream();
         while ((count = streamContent.read(buffer)) != -1)
         {
             content.write(buffer, 0, count);
         }
         byteContent = content.toByteArray();
         content.close();
	}
	
	public int getCode() {
		return code;
	}
	public int getContentLength() {
		return contentLength;
	}
	public Header[] getHeaders() {
		return headers;
	}
	public String getHeaderValue(String headerName){
		if(headers == null){
			return null;
		}
		else{
			for(Header h : headers){
				if(h.getName().equals(headerName)){
					return h.getValue();
				}
			}
		}
		return null;
	}
	public String getContentType() {
		return contentType;
	}
	/**
	 * Return response bytes content. Call to readBody() required first. 
	 * @return
	 */
	public byte[] getByteContent() {
		return byteContent;
	}
}
